import React, { useEffect, useState } from 'react'
import { Card, Row, Col, Input, Button, Table, Modal, message } from 'antd';
import axios from 'axios';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import request from '../../../utils/request';

export default function User() {
  //是否显示添加分类对话框
  const [isModalVisible, setIsModalVisible] = useState(false);
  //显示修改分类对话框
  const [isEditVisible, setIsEditVisible] = useState(false)
  //用户列表
  const [userList, setUserList] = useState([])
  //新分类的名称
  const [categoryName, setCategoryName] = useState('')
  //分类的ID
  const [catagoryID, setCategoryID] = useState(0)
  //分页器配置
  const [paginationOption, setPaginationOption] = useState({
    current: 1,
    defaultCurrent: 1,
    pageSizeOptions: ['2', '4', '6'],
    defaultPageSize: 4,
    total: 0,
    showSizeChanger: true,
    showTotal: (total) => `共${total}种`,
    onChange: (page, pageSize) => {
      paginationOption.defaultPageSize = pageSize
      paginationOption.current = page
      getCategory()
    },
    onShowSizeChange: (current, size) => {
      paginationOption.defaultCurrent = current
      paginationOption.defaultPageSize = size
      getCategory()
    }
  })

  useEffect(() => {
    getCategory()
  }, [])

  //获取分类列表
  function getCategory() {
    axios.get(`/v1/category`, {
      params: {
        pagesize: paginationOption.defaultPageSize,
        pagenum: paginationOption.current,

      }
    }).then(
      (res) => {
        console.log(res);
        setUserList(res.data.data)
        setPaginationOption({ ...paginationOption, total: res.data.total })
      },
      (err) => {
        console.log(err);
      }
    )
  }

  //确定添加分类
  const handleOk = async () => {
    const data = await request.post('/v1/category/add', { name: categoryName })
    console.log(data);
    if (data.status === 200) {
      message.success('添加分类成功')
      getCategory()
      setIsModalVisible(false);
      setCategoryName('')
    }
    else {
      message.error(data.message)
    }
  };
  //取消添加或者修改
  const handleCancel = () => {
    setIsModalVisible(false);
    setIsEditVisible(false)
  };
  //获取分类ID
  const getCategoryID = (id) => {
    setIsEditVisible(true)
    setCategoryID(id)
  }
  //确定修改分类
  const editOk = async (id) => {
    const data = await request.put(`/v1/category/${catagoryID}`, { name: categoryName })
    console.log(data);
    if (data.status === 200) {
      message.success('修改分类成功')
      getCategory()
      setIsEditVisible(false);
      setCategoryName('')
    }
    else {
      message.error(data.message)
    }

  };
  //获取分类名
  const getCategoryName = (e) => {
    setCategoryName(e.target.value)
  }
  //删除分类
  const deleteCategory = async (id) => {
    const data = await request.delete('/v1/category/' + id)
    console.log(data);
    if (data.status === 200) {
      getCategory()
      message.success('删除成功')
    }
    else {
      message.error(data.message)
    }
  }
  //确定删除
  function confirm(id) {
    Modal.confirm({
      title: '是否确定删除该分类',
      icon: <ExclamationCircleOutlined />,
      content: '一旦删除将不可逆转',
      onOk() { deleteCategory(id) },
      onCancel() {
        message.info('已取消删除')
      },
      okText: '确认',
      cancelText: '取消',
    });
  }

  //表格数据配置
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
    },
    {
      title: '分类名',
      dataIndex: 'name',
      key: 'name'
    },
    {
      title: '管理',
      dataIndex: '',
      key: '',
      render: (record) => {
        return (
          <>
            <Button type="primary" className='margin_right' onClick={() => getCategoryID(record.id)} >修改</Button>
            <Button type="danger" onClick={() => confirm(record.id)}>删除</Button>
          </>
        )
      }
    },

  ]
  return (
    <>
      <Card style={{}}>
        <Row gutter='20'>
          <Col span={3}><Button type="primary" onClick={() => setIsModalVisible(true)}>添加分类</Button></Col>
        </Row>
        <Table pagination={paginationOption} columns={columns} dataSource={userList} rowKey={i => i.id} bordered />
      </Card>
      <Modal title='添加分类' visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
        <Input placeholder="请输入分类名" onChange={(value) => getCategoryName(value)} allowClear maxLength={20} showCount />
      </Modal>
      <Modal title='修改分类' visible={isEditVisible} onOk={editOk} onCancel={handleCancel}>
        <Input placeholder="请输入分类名" onChange={(value) => getCategoryName(value)} allowClear maxLength={20} showCount />
      </Modal>
    </>
  )
}
